﻿using System.Diagnostics;
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using AndroidX.Core.App;
using AndroidX.Core.Content;
namespace AnyTap;

[Activity(Theme = "@style/Maui.SplashTheme", LaunchMode = LaunchMode.SingleInstance, MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
	protected override void OnStart()
	{
		base.OnStart();
		var permission = new string[]
		{
			Manifest.Permission.ReorderTasks,
			Manifest.Permission.ReadExternalStorage,
			Manifest.Permission.WriteExternalStorage,
		};

		if(OperatingSystem.IsAndroidVersionAtLeast(23))
		{
			SuperExec("settings put secure enabled_accessibility_services com.byo.anytap/.TapAccessibilityService");
			if(!Android.Provider.Settings.CanDrawOverlays(this))
			{
				SuperExec($"pm grant {PackageName} {Manifest.Permission.SystemAlertWindow}");
				if(!Android.Provider.Settings.CanDrawOverlays(this))
				{
					StartActivity(new Intent(Android.Provider.Settings.ActionManageOverlayPermission, Android.Net.Uri.Parse("package:" + PackageName)).SetFlags(ActivityFlags.NewTask));
				}
			}

			foreach(var item in permission)
			{
				if(ContextCompat.CheckSelfPermission(this, item) != Permission.Granted)
				{
					SuperExec($"pm grant {PackageName} {item}");
				}
			}

			if(permission.Any(s => ContextCompat.CheckSelfPermission(this, s) != Permission.Granted))
			{
				ActivityCompat.RequestPermissions(this, permission, 0);
			}
		}
	}

	private static void SuperExec(string cmd)
	{
		try
		{
			var su = Java.Lang.Runtime.GetRuntime().Exec("su"); //root权限执行命令
			var cmdbytes = System.Text.Encoding.ASCII.GetBytes($"{cmd}\nexit\n");
			su.OutputStream.Write(cmdbytes, 0, cmdbytes.Length);
			su.OutputStream.Close();
			su.WaitFor();
		}
		catch
		{ }
	}

	/// <summary>
	/// 触摸界面关闭软键盘
	/// </summary>
	public override bool DispatchTouchEvent(MotionEvent e)
	{
		if(e.Action == MotionEventActions.Down && CurrentFocus is EditText editText)
		{
			var rect = new Android.Graphics.Rect();
			editText.GetGlobalVisibleRect(rect);
			var location = new Rect(rect.ExactCenterX() - (rect.Width() / 2), rect.ExactCenterY() - (rect.Height() / 2), rect.Width(), rect.Height());
			if(!location.Contains(new Point(e.RawX, e.RawY)))
			{
				editText.ClearFocus();
				using var imm = (InputMethodManager)GetSystemService(InputMethodService);
				imm?.HideSoftInputFromWindow(editText.WindowToken, HideSoftInputFlags.None);
			}
		}

		return base.DispatchTouchEvent(e);
	}
}
